<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <meta http-equiv="X-UA-Compatible" content="ie=edge" />
  <link rel="stylesheet" href="style.css" />
  <title>My Blog</title>
</head>

<body>
  <div id="posts-container">
    <div class="post">
      <div class="number">1</div>
      <div class="post-info">
        <h2 class="post-title">sunt aut facere repellat provident occaecati excepturi optio reprehenderit</h2>
        <p class="post-body">quia et suscipit
          suscipit recusandae consequuntur expedita et cum
          reprehenderit molestiae ut ut quas totam
          nostrum rerum est autem sunt rem eveniet architecto</p>
      </div>
    </div>
  </div>
  <div class="loader">
    <div class="circle"></div>
    <div class="circle"></div>
    <div class="circle"></div>
  </div>
//111

  <script src="./axios.js"></script>

  <script>
    let currentPage = 1 // 当前页码，初始为1
    const pageSize = 5 // 每页数据量

    async function getData(page) {
      let obj = await axios({
        url: 'https://jsonplaceholder.typicode.com/posts',
        params: {
          _limit: pageSize,
          _page: page
        }
      })
      const str = obj.data.map(item => {
        return `
        <div class="post">
          <div class="number">${item.id}</div>
          <div class="post-info">
            <h2 class="post-title">${item.title}</h2>
            <p class="post-body">${item.body}</p>
          </div>
        </div>
        `
      }).join('')
      document.querySelector('#posts-container').innerHTML = str
    }

    // 加载动画 
    function showLoading() {
      document.querySelector('.loader').classList.add('show')
    }

    // 隐藏加载动画
    function hideLoading() {
      document.querySelector('.loader').remove('show')
    }

    // 是否正在加载
    let isLoading = false

    // 页面加载时获取第一页数据
    getData(currentPage)

    window.addEventListener('scroll', function () {
      // 获取滚动条滚动的距离
      const scrollTop = document.documentElement.scrollTop || document.body.scrollTop
      // 获取可视窗口高度
      const windowHeight = document.documentElement.clientHeight
      // 获取整个文档的高度 
      const documentHeight = document.documentElement.scrollHeight

      if (documentHeight - (scrollTop + windowHeight) <= 50) {
        // 距离底部50px时，加载下一页数据
        showLoading()
        currentPage++
        getData(currentPage)
        hideLoading()
      }
    })
  </script>
</body>

</html>